package com.example.server.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.server.bean.Employee;
import com.example.server.bean.MailLog;
import com.example.server.service.IEmployeeService;
import com.example.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ProjectName: yeb
 * Author: 别怿言
 * Date: 2023-02-11 16:40
 * Description：邮件定时发送任务
 */
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *每十秒执行一次定时任务
     * 参数：秒 分 时 日 月 周 年 （0/10：现在开始，每十秒执行一次）
     * （15,20,25,30）：枚举，一分钟第几秒执行任务
     * （15-25）：一分钟15-25秒执行任务
     * “*”：通配符
     * “？”：忽略参数，放置到最后
     */
    @Scheduled(cron = "0/10 * * * * ?")
    @Transactional
    public void SendMailTask(){
        List<MailLog> maillist = mailLogService.list(new QueryWrapper<MailLog>().
                eq("status", 0).lt("tryTime", LocalDateTime.now()));
        maillist.forEach((mailLog -> {
            if(3<=mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2));
            }else {
                mailLogService.update(new UpdateWrapper<MailLog>().set("count", mailLog.getCount() + 1)
                        .set("updateTime", LocalDateTime.now())
                        .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                        .eq("msgId",mailLog.getMsgId()));
                Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY, employee,
                        new CorrelationData(mailLog.getMsgId()));
            }
        }));
    }
}
